package thread;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class MyThreadPool{
    // 定义一个顺序表，将定义好的线程通过顺序表组织起来
    private List<Thread> threadList = new ArrayList<>();
    // 需要定义一个阻塞队列，持有任务
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);
    // 通过构造方法指定线程数，线程定义好之后就运行起来
    public MyThreadPool(int n){
        for(int i = 0; i < n; i++){
            Thread t = new Thread(() -> {
                try {
                    while(!Thread.currentThread().isInterrupted()){
                        // 从任务队列中取任务
                        // 因为持有任务的是阻塞队列，队列为空时，会自动阻塞
                        Runnable task = queue.take();
                        task.run();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            });
            t.start();
            threadList.add(t);
        }
    }

    // 使用 submit 向阻塞队列中添加任务
    public void submit(Runnable runnable) throws InterruptedException {
        // 阻塞队列为满的时候，能够自动阻塞
        queue.put(runnable);
    }
}


public class ThreadDemo29 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool threadPool = new MyThreadPool(4);
        for(int i = 0; i < 1000; i++){
            int n = i;
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("执行任务：" + n + ", 执行线程为：" + Thread.currentThread().getName());
                }
            });
        }
    }
}
